<template>
  <div class="wrapper">
    <div style="margin: 200px auto; background-color: #fff; width: 350px; height: 350px; padding: 20px; border-radius: 10px">
      <div style="margin: 20px 0; text-align: center; font-size: 24px"><b>登 录</b></div>
      <el-tabs v-model="activeTab" stretch>
        <el-tab-pane label="账号密码登录" name="account">
          <el-form :model="accountForm" :rules="accountRules" ref="accountForm">
            <el-form-item prop="username">
              <el-input placeholder="请输入账号" size="medium" prefix-icon="el-icon-user" v-model="accountForm.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input placeholder="请输入密码" size="medium" prefix-icon="el-icon-lock" show-password
                        v-model="accountForm.password"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="手机号登录" name="phone">
          <el-form :model="phoneForm" :rules="phoneRules" ref="phoneForm">
            <el-form-item prop="phone">
              <el-input placeholder="请输入手机号" size="medium" prefix-icon="el-icon-phone" v-model="phoneForm.phone"></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-input placeholder="请输入验证码" size="medium" prefix-icon="el-icon-message" v-model="phoneForm.code">
                <template #append>
                  <el-button @click="sendLoginCode" :disabled="codeDisabled">
                    {{ codeButtonText }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div style="margin: 10px 0; text-align: right">
        <el-button type="warning" size="small" autocomplete="off" @click="$router.push('/register')">注册</el-button>
        <el-button type="primary" size="small" autocomplete="off" @click="login">登录</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { setRoutes } from "@/router";

export default {
  name: "Login",
  data() {
    return {
      activeTab: 'account',
      accountForm: {},
      phoneForm: {},
      codeDisabled: false,
      codeButtonText: '获取验证码',
      countdown: 60,
      accountRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      phoneRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d{4,6}$/, message: '验证码格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      if (this.activeTab === 'account') {
        this.$refs['accountForm'].validate((valid) => {
          if (valid) {
            this.doLogin(this.accountForm, 'account')
          }
        })
      } else {
        this.$refs['phoneForm'].validate((valid) => {
          if (valid) {
            this.doLogin(this.phoneForm, 'phone')
          }
        })
      }
    },
    doLogin(form, type) {
      const url = type === 'account' ? '/user/login' : '/user/loginByPhone'
      this.request.post(url, form).then(res => {
        if (res.code == 200) {
          localStorage.setItem("user", JSON.stringify(res.data))
          localStorage.setItem("menus", JSON.stringify(res.data.menus))
          setRoutes()
          this.$message.success("登录成功")

          if (res.data.role === 'ROLE_USER') {
            this.$router.push("/front/Home")
          } else {
            this.$router.push("/")
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    sendLoginCode() {
      if (!this.phoneForm.phone) {
        this.$message.error('请输入手机号')
        return
      }
      if (!/^1[3-9]\d{9}$/.test(this.phoneForm.phone)) {
        this.$message.error('手机号格式不正确')
        return
      }

      this.codeDisabled = true
      this.request.get("/user/sms/send", { params: { phone: this.phoneForm.phone } }).then(res => {
        if (res.code === 200) {
          this.$message.success('验证码已发送')
          this.startCountdown()
        } else {
          this.$message.error(res.msg)
          this.codeDisabled = false
        }
      }).catch(() => {
        this.codeDisabled = false
      })
    },
    startCountdown() {
      const timer = setInterval(() => {
        this.countdown--
        this.codeButtonText = `${this.countdown}秒后重新获取`
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.codeButtonText = '获取验证码'
          this.countdown = 60
          this.codeDisabled = false
        }
      }, 1000)
    }
  }
}
</script>

<style scoped>
.wrapper {
  height: 100vh;
  background-image: linear-gradient(to bottom right, #FC466B, #3F5EFB);
  overflow: hidden;
}
</style>